package com.naiterui.ehp.bs.cms.modules.wms.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bp.bo.b2c.cms.CmsSkuBO;
import com.naiterui.ehp.bp.bo.b2c.cms.MedicineBO;
import com.naiterui.ehp.bp.bo.b2c.cms.ProductBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.beans.BeanUtil;
import com.naiterui.ehp.bs.cms.common.utils.ConfigUtil;
import com.naiterui.ehp.bs.cms.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.cms.common.vo.PageVO;
import com.naiterui.ehp.bs.cms.modules.wms.entity.PrescriptionPlatformProduct;
import com.naiterui.ehp.bs.cms.modules.wms.entity.Sku;
import com.naiterui.ehp.bs.cms.modules.wms.entity.SkuImage;
import com.naiterui.ehp.bs.cms.modules.wms.feign.IB2cPlatformFeignClient;
import com.naiterui.ehp.bs.cms.modules.wms.feign.IMedicineFeignClient;
import com.naiterui.ehp.bs.cms.modules.wms.feign.ISkuFeignClient;
import com.naiterui.ehp.bs.cms.modules.wms.mapper.MedicineMapper;
import com.naiterui.ehp.bs.cms.modules.wms.mapper.PrescriptionPlatformProductMapper;
import com.naiterui.ehp.bs.cms.modules.wms.mapper.ProductMapper;
import com.naiterui.ehp.bs.cms.modules.wms.mapper.SkuImageMapper;
import com.naiterui.ehp.bs.cms.modules.wms.mapper.SkuMapper;
import com.naiterui.ehp.bs.cms.modules.wms.service.IPlatformService;
import com.naiterui.ehp.bs.cms.modules.wms.service.ISkuService;
import com.naiterui.ehp.bs.cms.modules.wms.vo.PlatformSkuVO;
import com.naiterui.ehp.bs.cms.modules.wms.vo.PrescriptionPlatformProductVO;
import com.naiterui.ehp.bs.cms.modules.wms.vo.ProductInventoryParamVO;
import com.naiterui.ehp.bs.cms.modules.wms.vo.ProductVO;
import com.naiterui.ehp.bs.cms.modules.wms.vo.SkuVO;
import com.naiterui.ehp.bs.cms.modules.wms.vo.ThirdPartyProductVO;

import cn.hutool.core.collection.CollectionUtil;

/**
 * <pre>
 *
 * </pre>
 *
 * @author fangguanhong
 * @date 2021/4/9 4:29 PM
 * @since 1.0.0
 */
@Service
public class PlatformServiceImpl extends ServiceImpl<PrescriptionPlatformProductMapper, PrescriptionPlatformProduct> implements IPlatformService {

    @Autowired
    private PrescriptionPlatformProductMapper prescriptionPlatformProductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MedicineMapper medicineMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Value("${ehp.domain.img}")
    private String imgDomain;
    @Autowired
    private IB2cPlatformFeignClient ib2cPlatformFeignClient;
    @Autowired
    private IMedicineFeignClient medicineFeignClient;
    @Autowired
    private ISkuService skuService;
    @Value("${ehp.temppath}")
    private String tempUploadPath;
    @Autowired
    private ISkuFeignClient skuFeignClient;

    @Override
    public PageVO<ThirdPartyProductVO> queryPage(PageParamsVO pageParamsVO, ThirdPartyProductVO productVO) {
        QueryWrapper<ThirdPartyProductVO> entityWrapper = this.buildEntityWrapper(pageParamsVO, productVO);
        IPage<ThirdPartyProductVO> page = this.baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        return PageVO.toPageVo(page);
    }

    private QueryWrapper<ThirdPartyProductVO> buildEntityWrapper(PageParamsVO pageParamsVO, ThirdPartyProductVO thirdPartyProductVO) {
        QueryWrapper<ThirdPartyProductVO> entityWrapper = pageParamsVO.getEntityWrapper("t");

        // 商品编码
        String number = thirdPartyProductVO.getNumber();
        entityWrapper.eq(StringUtils.isNoneBlank(number), "t.number", number);

        // 药品名称
        String name = thirdPartyProductVO.getName();
        entityWrapper.like(StringUtils.isNoneBlank(name), "t.name", name);

        // 药品类型(西药、中成药、中草药)
        Integer type = thirdPartyProductVO.getType();
        entityWrapper.eq(null != type, "t.type", type);

        // 药品状态
        Integer status = thirdPartyProductVO.getStatus();
        entityWrapper.eq(null != status, "t.status", status);

        // 是否添加为商品
        Integer addMedicineTag = thirdPartyProductVO.getAddMedicineTag();
        entityWrapper.eq(null != addMedicineTag, "t.add_medicine_tag", addMedicineTag);

        return entityWrapper;
    }

    @Override
    public PlatformSkuVO thirdPartProductInfo(Long thirdId) throws BusinessException {
        PrescriptionPlatformProduct platformProduct = this.baseMapper.getById(thirdId);
        PlatformSkuVO result =
            PlatformSkuVO.builder()
                .number(platformProduct.getNumber())
                .name(platformProduct.getName())
                .commonName("")
                .specification(platformProduct.getSpec())
                .approvalNumber(platformProduct.getApprovalNumber())
                .standardCode(platformProduct.getStandardCode())
                .productionEnterprise(platformProduct.getProductionEnterprise())
                .skuName(platformProduct.getName() + " " + platformProduct.getSpec())
                .build();
        return result;
    }

    @Override
    public PlatformSkuVO skuInfo(Long skuId) throws BusinessException {
        PlatformSkuVO platformSkuVO = skuMapper.getSkuInfo(skuId);
        Long productId = platformSkuVO.getProductId();
        ProductVO productVO = productMapper.getById(platformSkuVO.getProductId());
        List<String> skuImages = skuImageMapper.getBySkuId(skuId, SkuImage.TYPE_THUMB);
        List<String> images = new ArrayList<>();
        String imgHost = ConfigUtil.getString("sku.images.url");
        if (CollectionUtil.isNotEmpty(skuImages)) {
            images = skuImages.stream().map(e -> imgHost + e.substring(1, e.length())).collect(Collectors.toList());
        }
        platformSkuVO.setImages(images);
        platformSkuVO.setName(Optional.ofNullable(productVO.getName()).orElse(""));
        platformSkuVO.setSkuName(Optional.ofNullable(productVO.getBrandName()).orElse("") + " " + Optional.ofNullable(productVO.getName()).orElse("") + " " + platformSkuVO.getSpecification());
        return platformSkuVO;
    }

    @Override
    public PageVO<PrescriptionPlatformProductVO> getPlatformProductPage(PageParamsVO pageParamsVO, PrescriptionPlatformProductVO platformProductVO)
        throws BusinessException {
        QueryWrapper<PrescriptionPlatformProductVO> entityWrapper = this.buildEntityWarper(pageParamsVO, platformProductVO);
        IPage<PrescriptionPlatformProductVO> page = this.skuMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        List<PrescriptionPlatformProductVO> list = page.getRecords();
        List<ProductInventoryParamVO> numbers = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            // 补充库存信息
            list.forEach(e -> numbers.add(ProductInventoryParamVO.builder().drugCode(e.getNumber()).build()));
        }
        // List<ProductInventoryVO> productInventory = ib2cPlatformFeignClient.getProductInventory(numbers);
        // Map<String, BigDecimal> inventoryMap = new HashMap<>();
        // if (CollectionUtil.isNotEmpty(productInventory)) {
        // inventoryMap = productInventory.stream()
        // .collect(Collectors.toMap(ProductInventoryVO::getDrugCode, ProductInventoryVO::getAvailableSumQty));
        // }
        // if (CollectionUtil.isNotEmpty(list)) {
        // for (PrescriptionPlatformProductVO e : list) {
        // // e.setInventory(inventoryMap.getOrDefault(e.getNumber(), new BigDecimal(0)));
        // e.setInventory(new BigDecimal(9999));
        // }
        // }
        page.setRecords(list);
        return PageVO.toPageVo(page);
    }

    public QueryWrapper<PrescriptionPlatformProductVO> buildEntityWarper(PageParamsVO pageParamsVO, PrescriptionPlatformProductVO platformProductVO) {
        QueryWrapper<PrescriptionPlatformProductVO> entityWrapper = pageParamsVO.getEntityWrapper("t");

        String number = platformProductVO.getNumber();
        entityWrapper.eq(StringUtils.isNoneBlank(number), "t.number", number);

        String name = platformProductVO.getName();
        entityWrapper.like(StringUtils.isNoneBlank(name), "t.name", name);

        Integer status = platformProductVO.getStatus();
        entityWrapper.eq(null != status, "t.status", status);

        Integer nmpaType = platformProductVO.getNmpaType();
        entityWrapper.eq(null != nmpaType, "p.nmpa_type", nmpaType);

        Long categoryId = platformProductVO.getCategoryId();
        entityWrapper.eq(null != categoryId, "m.category_id", categoryId);
        return entityWrapper;
    }

    @Override
    public void updateProduct(PlatformSkuVO param) throws BusinessException {
        MedicineBO medicineVO = new MedicineBO();
        BeanUtil.copyProperties(param, medicineVO);
        SkuVO skuVO = new SkuVO();
        BeanUtil.copyProperties(param, skuVO);
        String brandName = StringUtils.isNotEmpty(param.getBrandName()) ? param.getBrandName() : "";
        String spec = StringUtils.isNotEmpty(param.getSpecification()) ? param.getSpecification() : "";
        skuVO.setName(brandName + " " + param.getName() + " " + spec);
        skuVO.setDefaultSku(Sku.DEFAULT_SKU_YES);

        List<String> images = skuVO.getImages();
        String imgHost = ConfigUtil.getString("sku.images.url");
        List<String> replaceImages = images.stream().map(s -> s.replace(imgHost, this.tempUploadPath)).collect(Collectors.toList());
        skuVO.setImages(replaceImages);
        CmsSkuBO cmsSku = new CmsSkuBO();
        BeanUtils.copyProperties(skuVO, cmsSku);
        this.skuFeignClient.saveOrUpdate(ProductBO.builder().sku(cmsSku).medicine(medicineVO).build());

        //Long productId = this.medicineFeignClient.saveOrUpdate(medicineVO);
        //skuVO.setProductId(productId);
        //this.skuService.updateSku(skuVO);
    }
}
